class XJHEventBus {
  constructor() {
    this.eventBus = {};
  }

  on(eventName, eventCallback, thisArg) {
    let handlers = this.eventBus[eventName];
    if (!handlers) {
      handlers = [];
      this.eventBus[eventName] = handlers;
    }
    handlers.push({
      eventCallback,
      thisArg,
    });
  }

  off(eventName, eventCallback) {
    const handlers = this.eventBus[eventName];
    if (!handlers) return;
    const newHandlers = [...handlers];
    for (let i = 0; i < newHandlers.length; i++) {
      const handler = newHandlers[i];
      if (handler.eventCallback == eventCallback) {
        // 删除原来的东西对象里面的东西
        const index = handlers.indexOf(handler);
        handlers.splice(index, 1);
      }
    }
  }

  emit(eventName, ...payload) {
    const handlers = this.eventBus[eventName];
    if (!handlers) return;
    handlers.forEach((handler) => {
      handler.eventCallback.apply(handler.thisArg, payload);
    });
  }
}

const eventBus = new XJHEventBus();

const handleCallback = function (name = "xjh2") {
  console.log("监听abc", this, name);
};

eventBus.on("abc", handleCallback, { name: "xjh" });

eventBus.emit("abc", "xjh3");

// 时间总线的保存是根据 名字和它的执行函数两个地方进行操作的。。
eventBus.off("abc", handleCallback);

eventBus.emit("abc", "xjh3");
